package game_frame

import (
	"gamesdk/common/log"
	"gamesdk/inter"
	"sync"
)

type TraverseFunc func(key int, value *Table) bool

//桌子管理器
type TableManager struct {
	tables    []*Table
	sort      []int
	num       int
	lock      sync.Mutex
	waitGroup sync.WaitGroup
	interRoom inter.RoomInter
}

func NewTableManager(num, max, min int, room *Room, interRoom inter.RoomInter) *TableManager {
	defer log.Trace()()
	tableManage := &TableManager{
		num:       num,
		interRoom: interRoom,
	}
	tables := make([]*Table, num)
	tableManage.sort = make([]int, num)
	//初始化所有桌子
	for index := 0; index < len(tables); index++ {
		tables[index] = NewTable(index, max, min, room)
		tableManage.sort[index] = index
		go tables[index].funcRun(&tableManage.waitGroup)
	}
	tableManage.tables = tables
	return tableManage
}

/*
*遍历所有桌子
 */
func (this *TableManager) Traverse(f TraverseFunc) {
	this.lock.Lock()
	defer this.lock.Unlock()
	for index := 0; index < len(this.tables); index++ {
		if !f(index, this.tables[index]) {
			break
		}
	}
}

/*
*排序遍历
 */
func (this *TableManager) TraverseSort(f TraverseFunc) {
	this.lock.Lock()
	defer this.lock.Unlock()
	this.Sort()
	for index := 0; index < len(this.sort); index++ {
		if !f(index, this.tables[this.sort[index]]) {
			break
		}
	}
}

func (this *TableManager) Sort() {
	for i := 1; i < len(this.sort); i++ {
		for j := i; j > 0; j-- {
			if this.tables[this.sort[j]].count < this.tables[this.sort[j-1]].count {
				break
			}
			this.sort[j], this.sort[j-1] = this.sort[j-1], this.sort[j]
		}
	}
}

/*
*获取桌子
 */
func (this *TableManager) GetTableById(id int) *Table {
	defer log.Trace()()
	return this.tables[id]
}

func (this *TableManager) Reset() {
	defer log.Trace()()
	this.Traverse(func(key int, value *Table) bool {
		value.Reset()
		return true
	})
	this.waitGroup.Wait()
	this.Traverse(func(key int, value *Table) bool {
		value.status = g_TableFree
		value.count = 0
		value.adviceConfig = ""
		value.platformId = -1
		value.entranceRestrictions = -1
		value.roomID = -1
		value.level = 0
		value.roomProb = 0
		value.roomRate = 0
		for index := 0; index < len(value.chairs); index++ {
			value.chairs[index].Leave()
		}
		go value.funcRun(&this.waitGroup)
		//通知逻辑存储桌子
		//this.interRoom.InitTableFrameSink(value)
		return true
	})
	//log.Info("重置桌子成功")
}
